<?php

namespace App\Models\Traits;

use App\Models\{BaseDistrict, DiscountGoods};
use Illuminate\Support\Collection;

trait AddMoreInfoToGoods {
    /**
     * 为商品增加额外的信息，如店铺地址和折扣信息等
     *
     * @param Collection $recommendGoods
     * @param mixed ...$info
     * @return Collection
     */
    public static function add(Collection $recommendGoods, ...$info) : Collection
    {
        $districts = collect([]);
        $district_parents = collect([]);
        $discount_goods = collect([]);

        if (in_array('district', $info)) {
            $district_ids = $recommendGoods->pluck('district_id')->toArray();
            $districts = BaseDistrict::whereIn('district_id', $district_ids)->get();
            // 店铺所在的二级地址
            $district_parents = BaseDistrict::whereIn('district_id', $districts->pluck('district_parent_id')->toArray())->get();
        }

        if (in_array('discount', $info)) {
            $common_ids = $recommendGoods->pluck('common_id')->toArray();
            // 折扣商品信息
            $discount_goods = DiscountGoods::where('discount_goods_state', 1)->whereIn('common_id', $common_ids)->get();
        }

        $recommendGoods->each(function ($recommendGood) use ($districts, $district_parents, $discount_goods) {

            if (!$districts->isEmpty()) {
                $district = $districts->where('district_id', $recommendGood->district_id)->first();
                $recommendGood->district_name = $district->district_name;
                $recommendGood->district_parent_id = $district->district_parent_id;
            }

            if (!$district_parents->isEmpty()) {
                $district_parent = $district_parents->where('district_id', $district->district_parent_id)->first();
                $recommendGood->district_parent_name = $district_parent->district_name;
            }

            if (!$discount_goods->isEmpty()) {
                $discount_good = $discount_goods->where('common_id', $recommendGood->common_id)->first();
                $recommendGood->discount_price = $discount_good->discount_price ?? '';
            }

        });

        return $recommendGoods;
    }
}